'use strict';
/**
 * generate server controller
 */

var util = require('util');
var path = require('path');
var ScriptBase = require('../../lib/script-base.js');
var _ = require('underscore');
var engine = require('../../lib/engines');
/**
* Constructor
*/
var Generator = module.exports = function()
{
    ScriptBase.apply(this, arguments);

    this.sourceRoot(path.join(__dirname, path.join('..','templates','common','app','server','controllers')));

    if (!this.env.options.appPath) {
        this.env.options.appPath = path.join('.','app','server','controllers');
    }
    this.scriptSuffix = '.js';
    // console.log(arguments);
    if (this.interactive) {
        this.actions = {};
    }
    var config = this.getPanesConfig();
    if (!config) {
        var err = (this.lang==='cn') ? '' : 'Your installation might have been corrupted. Can not retrieve your original setup!';
        this.log.error(err);
        throw err;
    }
    else {
        this.lang = config['lang'];
    }
};

util.inherits(Generator, ScriptBase);

/**
 * ask the name of the action
 * actionName --> 1. simple string name
 *                2. As a path actionName/:id/:somethingElse
 */
Generator.prototype._nameOfAction = function()
{
    var _this = this;
    var cb = this.async();
    var lang = this.lang;
    this.prompt({
        type: 'input',
        message: (lang==='cn') ? '这个action的名字是什么?' : 'What do you call this action?',
        name: 'actionName'
    } , function(props) {
        if (props.actionName) {
            var action = props.actionName;
            if (action.indexOf('/') > -1) {
                var _actions = action.split('/');
                action = _actions[0];
                // if they have this complex routing then we inject an entry into the routes.js
                _this.actions[action] = {controller: _this.name , action: action , route: props.actionName};
            }
            else {
                _this.actions[props.actionName] = {controller: _this.name , action: action};
            }
            _this._actionInterface(action);
        }
        else {
            var msg = (lang==='cn') ? '必需要提交action的名字!' : 'No name provided! Please start again!';
            _this.log.error(msg);
        }
        cb();
    }.bind(this));
};

/**
 * ask the user what interface the user want for this action
 */
Generator.prototype._actionInterface = function(actionName)
{
    var _this = this;
    var cb = this.async();
    var lang = this.lang;
    var choices = ['all' , 'get' , 'post' , 'put' , 'delete'];
    this.prompt({
        type: 'list',
        choices: choices,
        name: 'listen',
        message: (lang==='cn') ? '这个action会用什么数据接口?' : 'What will this action listen?',
        default: 'all'
    } , function(props)
    {
        _this.actions[actionName].listen = props.listen;
        cb();
        _this._protectedAction(actionName);
    }.bind(this));
};

/**
 * protect this url or not
 */
Generator.prototype._protectedAction = function(actionName)
{
    var _this = this;
    var _this = this;
    var cb = this.async();
    var lang = this.lang;
    this.prompt({
        type: 'confirm',
        name: 'protect',
        message: (lang==='cn') ? '保护这个action?' : 'Protect this action?',
        default: false
    } , function(props)
    {
        _this.actions[actionName].protect = props.protect;
        cb();
        _this._exitInteractive();
    }.bind(this));
};

/**
 * exit or continue
 */
Generator.prototype._exitInteractive = function()
{
    var _this = this;
    var cb = this.async();
    var lang = this.lang;
    this.prompt({
        type: 'confirm',
        message: (lang==='cn') ? '完成?' : 'Finish?',
        name: 'exit',
        default: false
    } , function(props) {
        cb();
        if (!props.exit) {
            _this._nameOfAction();
        }
        else {
            _this._writeFile();
        }
    }.bind(this));
};

/**
 * generate new controller based on interactive.js template
 */
Generator.prototype._writeFile = function()
{
    var routes = {};
    var actionDef = [];
    // console.log(this.actions);
    _.each(this.actions , function(value , action)
    {
        // routes
        if (value.route) {
            delete value.route;
            routes[value.route] = value;
        }
        else {
            routes[action] = value;
        }
        // controller file
        var def = '';
        if (value.protect && value.listen!=='all') {
            def = '\t' + action + ':function(req , res) {\n';
            def += '\t\t\tthis.set({text: \'Hello\'});\n';
            def += '\t\t}\n';
        }
        else {
            def = '\t\'' + action + '\': {\n';
            def += '\t\tlisten: \'' + value.listen +'\',\n';
            def += '\t\tprotect: ' + (value.protect ? 'true' : 'false') + ',\n';
            def += '\t\taction: function(req , res) {\n';
            def += '\t\t\tthis.set({text: \'Hello\'});\n';
            def += '\t\t}\n\t}\n';
        }
        actionDef.push(def);
    });
    // write to the route file
    this.actionDef =  actionDef.join(',\n');
    // generate template
    this.appTemplate(
        'interactive',
        this.name,
        '.ctrl.' + this.scriptSuffix
    );
    // then we call route, otherwise it will mess up all the path defintion before
    this.generateNewRoute(routes);
};

/**
* generate a basic controller no route will be included
*/
Generator.prototype.createControllerFiles = function()
{
    var _this = this;
    if (_this.interactive) {
        return _this._nameOfAction();
    }
    this.helloWorld = this.name;
    this.appTemplate(
        'main',
        this.name,
        '.ctrl' + this.scriptSuffix
    );
};
